/**
 * @组件
 * @param {Object} options
 * @author gyp
 */
(function(ctx,factory){
	
	window.AtComponent = factory();
	
})(window,function(){
	/**
	 * 构造函数
	 * @param {Object} options
	 */
	function AtComponent(options){
		var me = this;
		me.options = options;
		me.initParam();
		me.bindEvent();
	}
	
	AtComponent.prototype = {
		initParam : function(){
			var me = this;
			var options = me.options;
			me.scope = options.scope;
			me.selArray = options.atMembers || [];
			me.container = document.querySelector("#" + options.containerId);
			me.handler = document.querySelector("#" + options.handlerId);
			
			/**
	         * at范围去重复
	         */
	        if(me.scope){
	            var result = [], hash = {};
	            for (var i = 0, elem; (elem = me.scope[i]) != null; i++) {
	                if (!hash[elem.id]) {
	                    result.push(elem);
	                    hash[elem.id] = true;
	                }
	            }
	            me.scope = result;
	        }
	        
	        /**
	         * 添加ALL
	         */
	        me.atMembers = me.scope.slice();
	        me.atMembers.unshift({
	        	id : 'ALL',
	        	name : 'ALL',
	        	role : 'ALL'
	        });
	        
	        me.atMembersMap = {};
	        if(!me.atMembers){
	            return;
	        }
	        for(var i = 0;i < me.atMembers.length;i++){
	            me.atMembersMap[me.atMembers[i].id] = me.atMembers[i];
	        }
		},
		init : function(){
			var me = this;
			/**
			 * 加载自定义范围
			 */
			var initScope = function(){
				if(me.scopeComp){
					me.scopeComp.open();
				}else{
					me.scopeComp = new AtScope({
						scope : me.atMembers,
						scopeMap : me.atMembersMap,
						selFunc : function(result){
							var showMembers = "";
							for (var i = 0; i < result.length; i++) {
								var item = result[i];
								showMembers += "@" + item.name + " ";
								me.selArray.push(item);
							}
							
							if(me.options.selFunc && typeof me.options.selFunc == 'function'){
								me.options.selFunc(result);
							}
	
							var content,preContent,nextContent,pos;
							content = me.container.value;
							pos = me.container.selectionStart;
							preContent = content.substring(0,pos);
							if(/@$/.test(preContent)){
								preContent = preContent.replace(/@$/,"");
							}
							nextContent = content.substring(pos);
							me.container.value = preContent + showMembers + nextContent;
							me.container.setSelectionRange(pos + showMembers.length,pos + showMembers.length);
						}
					});
				}
			}
			/**
			 * 默认范围：直接弹出选人界面
			 */
			var initNoScope = function(){
				//第二次点击的时候清空之前选择的数据
				if(me.selComp){
					cmp.selectOrgDestory(me.selComp.id);
				}
				/**
				 * 初始化选人组件
				 */
				me.selComp = cmp.selectOrg(me.options.containerId + 'cmp_selOrg', {
					type: 2,
					jump: false,
					maxSize: -1,
					minSize: 1,
					selectType: 'member',
					callback: function (result) {
						var resultObj = JSON.parse(result);
						var orgResult = resultObj.orgResult;
						if (orgResult.length > 0) {
							var selected = [];
							var showMembers = "";
							for (var i = 0; i < orgResult.length; i++) {
								var orgResultObj = orgResult[i];
								showMembers += "@" + orgResultObj.name + " ";
								selected.push({
									id : orgResultObj.id,
									name : orgResultObj.name
								})
							}
							if(me.options.selFunc && typeof me.options.selFunc == 'function'){
								me.options.selFunc({
									showMembers : showMembers
								});
							}
							/**
							 * 将结果插入到内容中
							 */
							var content,preContent,nextContent,pos;
							content = me.container.value;
							pos = me.container.selectionStart;
							preContent = content.substring(0,pos);
							if(/@$/.test(preContent)){
								preContent = preContent.replace(/@$/,"");
							}
							nextContent = content.substring(pos);
							me.container.value = preContent + showMembers + nextContent;
							me.container.setSelectionRange(pos + showMembers.length,pos + showMembers.length);
							me.selArray = me.selArray.concat(selected);
						}
					}
				});
			}
			
			if(me.options.scope){
				initScope();
			}else{
				initNoScope();
			}
		},
		/**
		 * 绑定事件
		 */
		bindEvent : function(){
			var me = this;
			var initFn = throttle(me.init,me);
			/**
			 * 点击@按钮
			 */
			if(me.handler){
				me.handler.addEventListener("click",function(){
					initFn();
				});
			}
			/**
			 * 手动输入@
			 */
			me.container.addEventListener("keyup",function(event){
				var content,caretPos,preContent;
				content = this.value;
				caretPos = this.selectionStart;
				preContent = content.substring(caretPos-1,caretPos);
				if(preContent == '@'){
					this.blur();
					setTimeout(function(){
						initFn();
					},200);
				}
			});
		},
		/**
		 * 动态添加@的范围
		 * @param {Object} members
		 */
		insertScope : function(members){
			var me = this;
			for(var i = 0;i < members.length;i++){
				me.scope.push(members[i]);
				me.atMembers.push(members[i]);
				me.atMembersMap[members[i].id] = members[i];
			}
			me.scopeComp.refresh();
		},
		/**
		 * 获取最终的结果
		 */
		getResult : function(){
			var me = this;
			//去重复
			var selected = me.selArray;
			var hash = {},result = [];
			for (var i = 0, elem; (elem = selected[i]) != null; i++) {
		        if (!hash[elem.id]) {
		            result.push(elem);
		            hash[elem.id] = true;
		        }
		    }
			
			var backResults = [];
			var content = this.container.value;
			for(var j = 0;j < result.length;j++){
				if(content.indexOf('@' + result[j].name) >= 0){
					backResults.push(result[j]);
					if(result[j].id === "ALL"){
						backResults = me.scope;
						break;
					}
				}
			}
			return backResults;
		}
	}
	
	/**
	 * @弹出层
	 */
	function AtScope(option){
		var me = this;
		me.option = option;
		this.init();
		me.backButton();
		me.initData(me.option.scope);
		me.bindEvent();
	}
	AtScope.prototype = {
		init : function(){
			var me = this;
			var container = document.createElement("div");
			container.classList.add("Animated-Container");
			container.classList.add("right-go");
			container.classList.add("animated");
			
			container.innerHTML = queryDom + contentDom + btnDom;
			document.getElementsByTagName('body')[0].appendChild(container);
			
			var header = container.querySelector(".cmp-segmented_title_content");
			var content = container.querySelector(".at-scope-content");
			var footer = container.querySelector(".cmp-block-with-box");
			
			me.container = container;
			content.style.height = window.innerHeight - header.offsetHeight - footer.offsetHeight + 'px';
			cmp('.cmp-search input').input();
			container.classList.add("cmp-active");
		},
		initData : function(data){
			var me = this;
			var html = cmp.tpl(listTpl,data);
			me.container.querySelector("ul.cmp-table-view").innerHTML = html;
			scroller = new cmp.iScroll('.at-scope-content', {hScroll: false, vScroll: true,useTransition:true});
			cmp.IMG.detect();
		},
		bindEvent : function(){
			var me = this;
			/**
			 * 取消按钮
			 */
			me.container.querySelector(".at-scope-cancel").addEventListener("click",function(){
				me.close();
			});
			/**
			 * 确定按钮
			 */
			me.container.querySelector(".at-scope-submit").addEventListener("click",function(){
				var selected = me.container.querySelectorAll(".at-scope-content input[type=checkbox]");
		        var result = [];
		        cmp.each(selected,function () {
		        	if(this.checked){
		        		var id = this.value;
		            	result.push(me.option.scopeMap[id]);
		        	}
		        });
		        if(me.option.selFunc && typeof me.option.selFunc == 'function'){
		        	me.option.selFunc(result);
		        }
		        me.close();
			});
			/**
			 * 搜索
			 */
			me.container.querySelector(".cmp-search input").addEventListener("input",function(){
				var inputValue = this.value;
				if(!inputValue){
					me.initData(me.option.scope);
					return;
				}
				me.initData(me.lookup(inputValue));
			});
			/**
			 * 查询框清空事件
			 */
			cmp(".cmp-search").on("tap",".cmp-icon-clear",function(){
				me.initData(me.option.scope);
			});
		},
		lookup : function(key){
			var me = this;
	        var data = me.option.scope;
	        var result = [];
	        for(var i = 0;i < data.length;i++){
	            if(data[i].name.indexOf(key) !== -1){
	                result.push(data[i]);
	            }
	        }
	        return result;
	   },
		backButton : function(){
			var me = this;
			cmp.backbutton();
	    	cmp.backbutton.push(function(){
	    		me.close();
	    	});
		},
		open : function(){
			var me = this;
			var checkBoxes = me.container.querySelectorAll(".at-scope-content input[type=checkbox]");
			cmp.each(checkBoxes,function(){
				this.checked = false;
			});
			me.container.classList.add("cmp-active");
			cmp.backbutton();
	    	cmp.backbutton.push(function(){
	    		me.close();
	    	});
		},
		close : function(){
			var me = this;
			me.container.classList.remove("cmp-active");
			cmp.backbutton.pop();
		},
		refresh : function(){
			var me = this;
			me.initData(me.option.scope);
		}
	}
	
	/**
	 * 头部html
	 */
	var queryDom = 	'<div class="cmp-segmented_title_content">' +
						'<form action="#" onsubmit="return false;">' +
							'<div class="cmp-content-title-search">' +
								'<div class="cmp-input-row cmp-search">' +
									'<input type="search" class="cmp-input-clear" placeholder="搜索">' +
								'</div>' +
							'</div>' +
						'</form>' +
					'</div>';
	
	/**
	 * 内容区域
	 */
	var contentDom = '<div class="at-scope-content">' +
						'<ul class="cmp-table-view">' +
						'</ul>' +
				     '</div>';
	
	/**
	 * 按钮区域
	 */
	var btnDom = '<div class="cmp-block-with-box cmp-block-with-btn" style="margin:0">' +
					'<button type="button" class="cmp-btn cmp-btn-primary2 cmp-btn-outlined cmp-btn-width40 at-scope-cancel" style="margin:0 5px;">取消</button>' +
					'<button type="button" class="cmp-btn cmp-btn-primary2 cmp-btn-width40 at-scope-submit" style="margin:0 5px;">确定</button>' +
				 '</div>';
	
	/**
	 * 列表模版
	 */
	var listTpl = 	'<% for(var i = 0,len = this.length;i < len; i++){ %>'+
		        	'<% var obj = this[i];%>'+	
						'<li class="cmp-table-view-cell cmp-checkbox cmp-left">' +
							'<input name="checkbox" type="checkbox" value="<%=obj.id%>" style="top:50%;transform:translate(0,-50%);">' +
							'<div style="display:flex;display:-webkit-flext;align-items:center;-webkit-align-items:center;">' +
								'<% if(obj.id !== "ALL"){ %>' +
									'<img class="cmp-img-cache" cmp-data="<%=obj.id%>" style="width:40px;height:40px;border-radius:50%;"/>' +
								'<% } %>' +
								'<div style="margin-left:5px;flex-grow:1;font-size:16px;color:#333;"><%=obj.name%></div>' +
								'<span class="at-scope-role" style="font-size:14px;color:#999;"><%=obj.role%></span>' +
							'</div>' +
						'</li>' +
					'<%}%>';
	
	/**
	 * 规定时间间隔执行函数
	 */
	function throttle(fun,ctx){
		var lastTime;
		return function(){
			var now = +new Date();
			if(!lastTime || (now - lastTime >= 500)){
				lastTime = now;
				var args = arguments;
				fun.apply(ctx,args);
			}
		}
	}
	
	return AtComponent;
});
